package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;

/**
 * <p>
 * 用户模块 Mapper 接口
 * </p>
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 用户注册
    @Insert("INSERT INTO user(u_name, u_password, u_phone_number, u_is_admin, u_balance) " +
            "VALUES(#{uName}, #{uPassword}, #{uPhoneNumber}, #{uIsAdmin}, #{uBalance})")
    @Options(useGeneratedKeys = true, keyProperty = "uId", keyColumn = "u_id")
    int insertUser(User user);

    @Select("SELECT * FROM user WHERE u_id = #{userId}")
    User selectById(Integer userId);

    // 根据用户名查询用户（登录用）
    @Select("SELECT u_id, u_name, u_password, u_phone_number, u_bio, u_is_admin, u_balance " +
            "FROM user WHERE u_name = #{username}")
    User selectByUsername(@Param("username") String username);

    // 检查用户名是否已存在
    @Select("SELECT COUNT(*) FROM user WHERE u_name = #{username}")
    int countByUsername(@Param("username") String username);

    // 更新用户信息
    @Update("UPDATE user SET " +
            "u_name = #{uName}, " +
            "u_password = #{uPassword}, " +
            "u_phone_number = #{uPhoneNumber}, " +
            "u_bio = #{uBio} " +
            "WHERE u_id = #{uId}")
    int updateUser(User user);


    @Select("<script>" +
            "SELECT * FROM user " +
            "WHERE u_is_admin = false " +
            "<if test='keyword != null and keyword != \"\"'>" +
            "   AND (u_name LIKE CONCAT('%', #{keyword}, '%') " +
            "   OR u_phone_number LIKE CONCAT('%', #{keyword}, '%') " +
            "   OR u_bio LIKE CONCAT('%', #{keyword}, '%')) " +  // 添加简介模糊查询
            "</if>" +
            "</script>")
    IPage<User> selectUserPage(Page<User> page, @Param("keyword") String keyword);

    @Update("UPDATE user SET u_bio = #{bio} WHERE u_id = #{userId}")
    int updateUserBio(@Param("userId") Integer userId, @Param("bio") String bio);

    @Update("UPDATE user SET u_password = #{password} WHERE u_id = #{userId}")
    int updateUserPassword(@Param("userId") Integer userId, @Param("password") String password);

    @Update("UPDATE user SET u_balance = u_balance + #{amount} WHERE u_id = #{userId}")
    int rechargeBalance(@Param("userId") Integer userId, @Param("amount") BigDecimal amount);

    @Update("UPDATE user SET u_balance = u_balance + #{amount} WHERE u_id = #{userId}")
    int addBalance(@Param("userId") Integer userId, @Param("amount") BigDecimal amount);

    @Update("UPDATE user SET u_balance = u_balance - #{amount} " +
            "WHERE u_id = #{userId} AND u_balance >= #{amount}")
    int deductBalance(@Param("userId") Integer userId, @Param("amount") BigDecimal amount);
}
